/*
 * 修改产品分类信息
 * @Author: ljb
 * @Date: 2018-03-27 17:53:27
 * @Last Modified by: kanglin
 * @Last Modified time: 2018-09-25 09:35:54
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>
  .ivu-form-item-content {
    img {
      width: 100px;
    }
  }
</style>
<template>
	<div class="v-admin-Product-edit">
		<Form
			ref="formValidate"
			:model="formValidate"
			:rules="ruleValidate"
			:label-width="labelWidth(80,120)"
			name="edit-form">

      <!-- 多语言不再使用 category 表名称 -->
			<!--<Form-item-->
				<!--:label="$t('category.name')"-->
				<!--prop="name">-->
				<!--<i-input-->
					<!--v-model="formValidate.name"-->
					<!--:placeholder="$t('category.please_enter_name')"-->
					<!--name="edit-name"-->
					<!--type="text"/>-->
			<!--</Form-item>-->

			<!--<Form-item-->
				<!--:label="$t('category.category_const')"-->
				<!--prop="const">-->
				<!--<i-input-->
					<!--v-model="formValidate.const"-->
					<!--:placeholder="$t('category.please_enter_const')"-->
					<!--name="edit-const"-->
					<!--type="text"/>-->
			<!--</Form-item>-->

      <Form-item
        required
        v-for="lang in languages"
        :key="'edit_category_names' + lang.id"
        :label="lang.name"
        :prop="'category_names[' + lang.id + ']'">
        <i-input
          v-model="formValidate.category_names[lang.id]"
          :placeholder="$t('common.placeholder',{'field': lang.name + $t('category.name')})"
          :name="'create-locale-name' + lang.id"
          type="text"/>
      </Form-item>

			<Form-item
				:label="$t('category.icon')"
				prop="icon">
				<Uploader
					ref="icon"
					:default.sync="icon_src"
					@on-remove="(file)=>{handleRemove('icon',file)}"
					@on-change="(file)=>{handleChange('icon',file)}">
					{{ $t('common.pic_tip') + $t('category.img_tip') }}
				</Uploader>
			</Form-item>

			<!-- <Form-item
				:label="$t('category.icon_active')"
				prop="icon_active">
				<Uploader
					ref="icon_active"
					:default.sync="icon_active_src"
					@on-remove="(file)=>{handleRemove('icon_active',file)}"
					@on-change="(file)=>{handleChange('icon_active',file)}">
					{{ $t('common.pic_tip') }}
				</Uploader>
			</Form-item>

			<Form-item
				:label="$t('category.relative_asset')"
				prop="has_asset">
				<i-switch
					v-model="formValidate.has_asset"
					true-value="1"
					false-value="0"
					name="edit-has_asset">
					<Icon
						slot="open"
						type="android-done"/>
					<Icon
						slot="close"
						type="android-close"/>
				</i-switch>
			</Form-item> -->

			<FormItem :label="$t('category.type')">
				<RadioGroup v-model="formValidate.has_asset">
					<Radio label="1">{{ $t('category.makeup') }}</Radio>
					<Radio label="0">{{ $t('category.skincare') }}</Radio>
				</RadioGroup>
			</FormItem>

			<Form-item
				:label="$t('category.priority')"
				prop="priority">
				<InputNumber
					:max="100000"
					:min="0"
					v-model="formValidate.priority"
					:placeholder="$t('category.please_enter_priority')"
					name="edit-priority"/>
			</Form-item>

			<Form-item>
				<Button
					type="primary"
					@click="handleSubmit('formValidate')">
					{{ $t('common.update') }}
				</Button>
			</Form-item>

		</Form>
	</div>
</template>

<script>
import labelWidthMixin from 'src/views/mixins/labelWidthMixin';
import { validateUpdateImage } from 'src/validate'; // 引入校验文件
import Uploader from 'src/views/component/Uploader';

export default {
	name: 'AdminCategoryEdit',
	components: {
		Uploader,
	},
	mixins: [labelWidthMixin],
	props: {
		categoryDetail: {
			type: Object,
			default() {
				return {};
			},
		},
    languages: {
      type: Array,
      required: true,
    }
	},
  mounted(){
    this.addLocaleValidateRules();
  },
	data() {
		return {
			formValidate: {
				name: '', // 类别名称

				const: '', // 英文命名

				parent_id: '0', // 父类ID

				priority: 1, // 优先级

				icon: '', // 普通图标

				icon_active: '', // 高亮图标

				has_asset: '0', // 关联素材

        category_names: {} // 多语言名称
			}, // 更新产品分类时的表单

			ruleValidate: { // 表单验证规则
				icon: [
					{ validator: validateUpdateImage, trigger: 'blur,change' },
				],

				icon_active: [
					{ validator: validateUpdateImage, trigger: 'blur,change' },
				],
			},

			icon_active_src: '', // 后端返回的图片url

			icon_src: '', // 后端返回的图片url

		};
	},

	created() {
		this.initFormData();
	},

	methods: {
    addLocaleValidateRules() {
      this.languages.forEach(lang => {
        this.ruleValidate['category_names[' + lang.id + ']'] = [
          {
            required: true,
            message: this.$t('validate.required', { field: this.$t('category.name') }),
            trigger: 'blur,change',
          },
        ]
      });
    },
		/**
		 * 初始化表单数据
		 * @return {undefined}
		 */
		initFormData() {
			if (this.categoryDetail) {
				this.formValidate.name = this.categoryDetail.name;

				this.formValidate.parent_id = String(this.categoryDetail.parent_id);

				this.formValidate.const = this.categoryDetail.const;

				this.formValidate.priority = this.categoryDetail.priority;

				this.formValidate.has_asset = String(this.categoryDetail.has_asset);

				this.formValidate.icon = this.categoryDetail.icon;

				this.formValidate.icon_active = this.categoryDetail.icon_active;

        this.categoryDetail.category_descriptions.forEach(({language_id, name}) => {
          this.formValidate.category_names[language_id] = name;
        })

				this.icon_src = this.categoryDetail.icon;

				this.icon_active_src = this.categoryDetail.icon_active;
			}
		},

		/**
		 * 删除图片
		 * @param {String} field {icon}
		 * @return {undefined}
		 */
		handleRemove(field) {
			this.formValidate[field] = null;
			// this.$refs.formValidate.validateField(field);
		},

		/**
		 * 选择图片
		 * @param {String} field {icon}
		 * @param {String} file {选择文件的对象}
		 * @return {undefined}
		 */
		handleChange(field, { file }) {
			this.formValidate[field] = file;
			// this.$refs.formValidate.validateField(field);
		},

		/**
     * 重置部分信息
     * @return {undefined}
     */
		handleReset() {
			this.icon_info.name = '';

			this.icon_info.url = '';

			this.icon_active_info.name = '';

			this.icon_active_info.url = '';
		},


		/**
     * 提交表单
     * @param  {string} name {表单的ref}
     * @return {undefined}
     */
		handleSubmit(name) {
			this.$refs[name].validate((valid) => {
				if (valid) {
					this.updateCategory();
				} else {
					this.$Message.error(this.$t('common.exist_empty_field'));
				}
			});
		},

		/**
         * 更新分类
         * @return {undefined}
         */
		updateCategory() {
			this.$emit('update', this.categoryDetail.id, this.formDataCreate());
		},

		/**
         * 手动拼接formdata数据
         * @return {Object}
         */
		formDataCreate() {
			const new_object = {
				_method: 'PUT',

				name: this.formValidate.name,

				const: this.formValidate.const,

				parent_id: this.formValidate.parent_id,

				priority: this.formValidate.priority,

				has_asset: this.formValidate.has_asset,
			};

      Object.keys(this.formValidate.category_names).forEach((lang_id, idx) => {
        new_object[`category_names[${idx}][language_id]`] = lang_id;
        new_object[`category_names[${idx}][name]`] = this.formValidate.category_names[lang_id];
      })

			if (this.formValidate.icon !== this.categoryDetail.icon) {
				new_object.icon = this.formValidate.icon;
			}

			if (this.formValidate.icon_active !== this.categoryDetail.icon_active) {
				new_object.icon_active = this.formValidate.icon_active;
			}

			const form_data = new FormData();

			Object.keys(new_object).forEach((key) => {
				form_data.append(key, new_object[key]);
			});

			return form_data;
		},

	},
};
</script>
